package com.adopapa.ethexplorer.service;

import java.io.IOException;
import java.math.BigInteger;
import java.util.LinkedHashMap;
import java.util.Map;

import org.web3j.crypto.Credentials;
import org.web3j.crypto.ECKeyPair;
import org.web3j.crypto.Keys;
import org.web3j.crypto.RawTransaction;
import org.web3j.crypto.TransactionEncoder;
import org.web3j.crypto.Wallet;
import org.web3j.crypto.WalletFile;
import org.web3j.protocol.ObjectMapperFactory;
import org.web3j.utils.Numeric;

import com.fasterxml.jackson.databind.ObjectMapper;

public class WalletManager {

	/**
	 * 创建钱包
	 * 
	 * @param password 密码
	 */
	public static Map<String, String> createStandardWallet(String password) throws Exception {

		ECKeyPair ecKeyPair = Keys.createEcsmKeyPair();
		WalletFile walletFile = Wallet.createStandard(password, ecKeyPair);

		ObjectMapper objectMapper = ObjectMapperFactory.getObjectMapper();

		String jsonStr = objectMapper.writeValueAsString(walletFile);

		Map<String, String> result = new LinkedHashMap<String, String>();
		result.put("address", "0x".concat(walletFile.getAddress()));
		result.put("privateKey", "0x".concat(Numeric.toHexString(ecKeyPair.getPrivateKey().toByteArray())));
		result.put("publicKey", "0x".concat(Numeric.toHexString(ecKeyPair.getPublicKey().toByteArray())));
		result.put("keystore", jsonStr);

		return result;
	}

	public static Map<String, String> createLightWallet(String password) throws Exception {

		ECKeyPair ecKeyPair = Keys.createEcsmKeyPair();
		WalletFile walletFile = Wallet.createLight(password, ecKeyPair);
		Wallet.createLight(password, ecKeyPair);
		ObjectMapper objectMapper = ObjectMapperFactory.getObjectMapper();

		String jsonStr = objectMapper.writeValueAsString(walletFile);

		Map<String, String> result = new LinkedHashMap<String, String>();
		result.put("address", walletFile.getAddress());
		result.put("privateKey", Numeric.toHexString(ecKeyPair.getPrivateKey().toByteArray()));
		result.put("publicKey", Numeric.toHexString(ecKeyPair.getPublicKey().toByteArray()));
		result.put("keystore", jsonStr);

		return result;
	}

	/**
	 * 解密keystore 得到私钥
	 *
	 * @param keystore
	 * @param password
	 */
	public static String decryptWallet(String keystore, String password) throws Exception {
		String privateKey = null;
		ObjectMapper objectMapper = ObjectMapperFactory.getObjectMapper();
		WalletFile walletFile = objectMapper.readValue(keystore, WalletFile.class);
		ECKeyPair ecKeyPair = Wallet.decrypt(password, walletFile);
		privateKey = ecKeyPair.getPrivateKey().toString(16);
		
		
		
		return privateKey;
	}
	
	

	/**
	 * 签名交易
	 */
	public static String signTransaction(BigInteger nonce, BigInteger gasPrice, BigInteger gasLimit, String to,
			BigInteger value, String data, String privateKey) throws IOException {
		RawTransaction rawTransaction = RawTransaction.createTransaction(nonce, gasPrice, gasLimit, to, value, data);

		if (privateKey.startsWith("0x")) {
			privateKey = privateKey.substring(2);
		}
		System.out.println(privateKey);
		ECKeyPair ecKeyPair = ECKeyPair.create(new BigInteger(privateKey, 16));
		Credentials credentials = Credentials.create(ecKeyPair);

		byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, credentials);

		String hexValue = Numeric.toHexString(signedMessage);
//		System.err.println(hexValue);
//		RawTransaction decode = TransactionDecoder.decode(hexValue);
//		System.err.println(decode);
//		System.err.println(rawTransaction);

		return hexValue;
	}
	
	
//	public static void testTransaction() {
//		BigInteger nonce;
//		EthGetTransactionCount ethGetTransactionCount = null;
//		//"0x59e9f0c95fbf192f66609acccbe13c0719da9dbd", "0x3d889ca41d8e7d6cfe9230fe3a820f98d97bd853"
//		//String from = "0x59e9f0c95fbf192f66609acccbe13c0719da9dbd".toLowerCase();
//		//String to = "0x3d889ca41d8e7d6cfe9230fe3a820f98d97bd853".toLowerCase();
//		// ["0xdef6f56244a443132c23ca05c1dbb01a105cd131", "0xe77ce3e2ddb5bf795fe3526a761807494dcde21d"]
//		String from = "0x25e63ae307A51c70493D29DDf145c2d7113fA943".toLowerCase();
//		String to = "0xe77ce3e2ddb5bf795fe3526a761807494dcde21d".toLowerCase();
//		address = from;
//		try {
//			ethGetTransactionCount = web3j.ethGetTransactionCount(address, DefaultBlockParameterName.PENDING).send();
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//		if (ethGetTransactionCount == null)
//			return;
//		nonce = ethGetTransactionCount.getTransactionCount();
//		BigInteger gasPrice = Convert.toWei(BigDecimal.valueOf(3), Convert.Unit.GWEI).toBigInteger();
//		BigInteger gasLimit = BigInteger.valueOf(30000);
//		
//		DefaultGasProvider gasProvider = new DefaultGasProvider();
////		String to = "0x9022c9d4777804e395fb4289566d71bd5c49b5cb".toLowerCase();
//		BigInteger value = Convert.toWei(BigDecimal.valueOf(0.5), Convert.Unit.ETHER).toBigInteger();
//		String data = "";
//		byte chainId = ChainId.ROPSTEN;// 测试网络
//		chainId = (byte) 1000;
//		String privateKey = ColdWallet.privateKey;
//		String signedData;
//		try {
//			signedData = signTransaction(nonce, //
//					gasProvider.getGasPrice(), //
//					gasProvider.getGasLimit(), //
//					to, value, data, chainId, privateKey);
//			if (signedData != null) {
//				EthSendTransaction ethSendTransaction = web3j.ethSendRawTransaction(signedData).send();
//				System.out.println(ethSendTransaction.getTransactionHash());
//			}
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//	}


}
